﻿using DocumentFormat.OpenXml.Spreadsheet;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using xiaoxiong.KYJDAL.Services;
using xiaoxiong.ScadaProModbusRtu.Common;

namespace xiaoxiong.ScadaProModbusRtu
{
    public partial class FrmReport : Form
    {
        public FrmReport()
        {
            InitializeComponent();

            cbx_ReportType.SelectedIndexChanged += Cbx_ReportType_SelectedIndexChanged;

            cbx_ReportType.Items.Add("小时报表");
            cbx_ReportType.Items.Add("日报表");
            cbx_ReportType.SelectedIndex = 0;


            if(CommonMethods.plcDevice != null)
            {
                InitDgv();
            }
        }

        /// <summary>
        /// 所有归档变量的名称和描述的字典集合
        /// </summary>
        private Dictionary<string, string> columnList = new Dictionary<string, string>();

        private ActualDataService ActualDataService = new ActualDataService();
        
        //查询最大值条件
        private List<string> maxCondition = new List<string>();
        private List<string> minCondition = new List<string>();
        private List<string> avgCondition = new List<string>();
        private void InitDgv()
        {
            this.dgv_Main.Columns.Clear();
            columnList.Clear();
            columnList.Add("InsertTime", "日期时间");

            foreach (var item in CommonMethods.plcDevice.StoreVarList)
            {
                columnList.Add(item.VarName, item.Comments);

                maxCondition.Add($"MAX({item.VarName})");
                minCondition.Add($"MIN({item.VarName})");
                avgCondition.Add($"AVG({item.VarName})");
            }

            foreach (var item in columnList.Keys)
            {
                //创建-个DataGridViewTextBoxColumn对象
                DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
                //属性赋值
                column.HeaderText = columnList[item];
                column.ReadOnly = true;
                column.Width = item == "InsertTime" ? 170 : 140;
                column.SortMode = DataGridViewColumnSortMode.NotSortable;
                this.dgv_Main.Columns.Add(column);
            }


        }

        private void Cbx_ReportType_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (cbx_ReportType.SelectedIndex)
            {
                case 0:
                    this.dtp_Time.CustomFormat = "yyyy-MM-dd HH:00:00";
                    break;
                case 1:
                    this.dtp_Time.CustomFormat = "yyyy-MM-dd 00:00:00";
                    break;  
                default:
                    this.dtp_Time.CustomFormat = "yyyy-MM-dd 00:00:00";
                    break;
            }
        }

        private void btn_Find_Click(object sender, EventArgs e)
        {
            this.dgv_Main.Rows.Clear();

            List<string> startList = new List<string>();
            List<string> endList = new List<string>();

            List<string> conditions = this.rdb_Max.Checked ? maxCondition : this.rdb_Min.Checked ? minCondition : avgCondition;

            DateTime dateTime = Convert.ToDateTime(this.dtp_Time.Text);

            switch (this.cbx_ReportType.SelectedIndex)
            {
                case 0:
                    for (int i = 0; i < 60; i++)
                    {
                        startList.Add(dateTime.AddMinutes(i).ToString("yyyy-MM-dd HH:mm:ss"));
                        endList.Add(dateTime.AddMinutes(i + 1).ToString("yyyy-MM-dd HH:mm:ss"));
                    }
                    break;

                case 1:
                    for (int i = 0; i < 24; i++)
                    {
                        startList.Add(dateTime.AddHours(i).ToString("yyyy-MM-dd HH:mm:ss"));
                        endList.Add(dateTime.AddHours(i + 1).ToString("yyyy-MM-dd HH:mm:ss"));
                    }
                    break;
                default:
                    break;
            }

            //获取到了时间区间以及条件

            Task.Factory.StartNew(() =>
            {
                Task<DataTable>[] taskList = new Task<DataTable>[startList.Count];

                for (int i = 0; i < startList.Count; i++)
                {
                    taskList[i] = Task.Factory.StartNew((index) =>
                    {
                        var dt = ActualDataService.QueryReportDataByCondition(
                            startList[(int)index], endList[(int)index],
                            conditions, "table" + index.ToString());
                        dtAll = dt;
                        return dt;
                    }, i);
                }

                Task<DataTable[]> task = Task.WhenAll(taskList);

                var data = GetAllDataTable(task.Result);

                this.Invoke(new Action(() =>
                {
                    for (int i = 0; i < data.Rows.Count; i++)
                    {
                        int rowCount = this.dgv_Main.Rows.Add();
                        this.dgv_Main.Rows[rowCount].Cells[0].Value = startList[rowCount];
                        for (int j = 0; j < data.Columns.Count; j++)
                        {
                            object result = data.Rows[rowCount][j];
                            if (result is DBNull)
                            {
                                this.dgv_Main.Rows[rowCount].Cells[j + 1].Value = 0.0;
                            }
                            else
                            {
                                try
                                {
                                    this.dgv_Main.Rows[rowCount].Cells[j + 1].Value = Convert.ToDouble(result).ToString("f2");
                                }
                                catch
                                {
                                    this.dgv_Main.Rows[rowCount].Cells[j + 1].Value = 0.0;
                                }            
                            }
                           
                        }
                    }
                }));
            });
        }

        /// <summary>
        /// 将多个相同的表结构合并成一个数据表
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        private DataTable GetAllDataTable(DataTable[] dt)
        {
            DataTable resultTable = dt[0].Clone();

            object[] rowDt = new object[resultTable.Columns.Count];

            for(int i = 0;i < dt.Length;i++)
            {
                for(int j = 0;j < dt[i].Rows.Count;j++)
                {
                    dt[i].Rows[j].ItemArray.CopyTo(rowDt,0);
                    resultTable.Rows.Add(rowDt);
                }
            }
            return resultTable;
        }

        DataTable dtAll = new DataTable();
        //导出
        private void btn_Explot_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "xls文件(*.xls)|*.xls|所有文件|*.*";
            saveFileDialog.Title = "导出数据报表";
            saveFileDialog.FileName = "数据报表" + DateTime.Now.ToString("yyyyMMddHHmmss");
            saveFileDialog.DefaultExt = "xls";
            saveFileDialog.AddExtension = true;
            // 显示对话框并判断是否确认保存
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    // 获取要导出的数据（这里替换成你实际的数据获取方式）
                    DataTable data = dtAll;
                    // 使用 NPOI 库生成 Excel 文件
                    using (FileStream fs = new FileStream(saveFileDialog.FileName, FileMode.Create))
                    {
                        // 创建 HSSFWorkbook 对象（适用于 .xls 格式）
                        HSSFWorkbook workbook = new HSSFWorkbook();
                        ISheet sheet = workbook.CreateSheet("Sheet1");

                        // 创建表头
                        IRow headerRow = sheet.CreateRow(0);
                        for (int i = 0; i < data.Columns.Count; i++)
                        {
                            headerRow.CreateCell(i).SetCellValue(data.Columns[i].ColumnName);
                        }

                        // 填充数据
                        for (int rowIdx = 0; rowIdx < data.Rows.Count; rowIdx++)
                        {
                            IRow dataRow = sheet.CreateRow(rowIdx + 1);
                            for (int colIdx = 0; colIdx < data.Columns.Count; colIdx++)
                            {
                                dataRow.CreateCell(colIdx).SetCellValue(data.Rows[rowIdx][colIdx].ToString());
                            }
                        }

                        // 写入文件流
                        workbook.Write(fs);
                    }

                    MessageBox.Show("导出成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"导出失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }            
        }

        private DataTable GetExportData(DataTable dataTable)
        {
            return dataTable;
        }

        //打印
        private void btn_print_Click(object sender, EventArgs e)
        {

        }
    }
}
